package cn.stylefeng.guns.modular.hx.basic.controller;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicUnitCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicUnitCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.node.ZTreeNode;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoodsCode;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicGoodsCodeParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicGoodsCodeResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsCodeService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 商品分类控制器
 *
 * @author zhucx
 * @Date 2024-01-10 15:07:34
 */
@Controller
@RequestMapping("/hxBasicGoodsCode")
public class HxBasicGoodsCodeController extends BaseController {

    private String PREFIX = "/hx/basic/hxBasicGoodsCode";

    @Autowired
    private HxBasicGoodsCodeService hxBasicGoodsCodeService;
    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;
    @Autowired
    private UserService userService;
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicXlbOauth2tokenService basicXlbOauth2tokenService;

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("")
    public String index() {

        return PREFIX + "/hxBasicGoodsCode.html";
    }

    // 跳转到拉取商品分类页面
    @RequestMapping("pickProducts")
    public String pickProducts(Model model) {
        User user = userService.getcurrentUser();
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(user.getDeptId(),user.getDeliverId(),user.getOperateId()));
        return PREFIX + "/pickProducts.html";
    }




    /**
     * 拉取新零帮商品信息
     *
     * @author
     * @Date 2023-04-20
     */
    @RequestMapping("/products")
    @ResponseBody
    public ResponseData products(@RequestParam("updateTime") String updateTime , Integer customerId) {
        User user = userService.getcurrentUser();
        BasicCustomer r = basicCustomerService.getById(customerId);
        if(ToolUtil.isEmpty(r.getGsnumber())) {
            return ResponseData.error("请维护新零帮公司号");
        }

        //        String url = "https://test-api.xlbsoft.com/api/hxl.open.itemcategory.findbyupdatetime";
      String url = "https://hxl-api.xlbsoft.com/api/hxl.open.itemcategory.findbyupdatetime";


        // 创建请求参数对象
        JSONObject json = new JSONObject();

        json.put("update_time", updateTime);


        BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
        oauth2tokenParam.setDeliverId(r.getDeliverId());
        oauth2tokenParam.setGsnumber(r.getGsnumber());
        BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

        String response = HttpRequest.post(url)
                .header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
                .body(json.toString()).execute().body();
        //System.out.println(response);
        JSONObject jsonObject = new JSONObject(response);

        if (jsonObject.get("code").toString().equals("0")) {
            JSONArray data = jsonObject.getJSONArray("data");
            List<HxBasicGoodsCode> batchToAdd = new ArrayList<>(); // 用于存储每一页的数据，批量添加到系统中

          for (Object item :data){
              HxBasicGoodsCodeParam hxBasicGoodsCode = new HxBasicGoodsCodeParam();
              Object  id= ((JSONObject) item).get("id");// 商品分类id
              Object  parentId= ((JSONObject) item).get("parent_id");// 父类id
              Object  name= ((JSONObject) item).get("name");// 商品类别名称
              Object  level= ((JSONObject) item).get("level");// 商品类别层级
              Object  status= ((JSONObject) item).get("status");// 商品类别启用状态
              Object  categoryCode= ((JSONObject) item).get("category_code");// 商品类别代码名称
              Object  shorthandCode= ((JSONObject) item).get("shorthand_code");// 商品类别速记码



// 声明一个StringBuilder用于构建pids值
              HxBasicGoodsCodeParam hxBasicGoodsCodeParam = new HxBasicGoodsCodeParam();
              hxBasicGoodsCodeParam.setXlbCategoryId(parentId.toString());
              hxBasicGoodsCodeParam.setDeptId(user.getDeptId());
              hxBasicGoodsCodeParam.setDeliverId(user.getDeliverId());
              hxBasicGoodsCodeParam.setOperateId(user.getOperateId());
              HxBasicGoodsCodeResult basicUnitCodeResult = hxBasicGoodsCodeService.findBySpec(hxBasicGoodsCodeParam);

//              HxBasicGoodsCode hxBasicGoodsCode1 = hxBasicGoodsCodeService.lambdaQuery()
//                      .eq(HxBasicGoodsCode::getXlbCategoryId, parentId.toString())
//                      .one();
              if(basicUnitCodeResult!=null){
                     if (parentId.toString().equals(basicUnitCodeResult.getXlbCategoryId())){
//                         String formattedString = "[" + hxBasicGoodsCode1.getPid() + "],[" + hxBasicGoodsCode1.getId() + "],[" + hxBasicGoodsCode1.getPids() + "]";                         String formattedString = String.format("[%s],[%s],[%s]", hxBasicGoodsCode1.getPid(), hxBasicGoodsCode1.getId(), hxBasicGoodsCode1.getPids());
//                         hxBasicGoodsCode.setPids(formattedString);

                         String formattedString = String.format("[%s],[%s],%s", basicUnitCodeResult.getPid(),basicUnitCodeResult.getId(),basicUnitCodeResult.getPids());
                         String[] values = formattedString.split(",");
                         Set <String> uniqueValues = new LinkedHashSet <>();
                         for (String value : values) {
                             if (!value.isEmpty()) {
                                 uniqueValues.add(value);
                             }
                         }
                         String deduplicatedString = String.join(",", uniqueValues);

                         hxBasicGoodsCode.setPids(deduplicatedString);

                         hxBasicGoodsCode.setPid((long)basicUnitCodeResult.getId());
                     }

              }

              hxBasicGoodsCode.setXlbCategoryId(id.toString());
              hxBasicGoodsCode.setCodeName(name.toString());
              hxBasicGoodsCode.setCodeNumber(categoryCode.toString());
              hxBasicGoodsCode.setStatus(status.toString());
              hxBasicGoodsCode.setDeptId(user.getDeptId());
              hxBasicGoodsCode.setDeliverId(user.getDeliverId());
              hxBasicGoodsCode.setCreateUser(user.getName());

              hxBasicGoodsCodeService.add(hxBasicGoodsCode);
          }
//          hxBasicGoodsCodeService.saveBatch(batchToAdd);

        }

        return ResponseData.success();
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/hxBasicGoodsCode_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/hxBasicGoodsCode_edit.html";
    }

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsCodeParam.setDeptId(user.getDeptId());
    	hxBasicGoodsCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicGoodsCodeParam.setCreateUser(user.getName());

        if (ToolUtil.isEmpty(hxBasicGoodsCodeParam.getPid()) || hxBasicGoodsCodeParam.getPid().equals(0L)) {
        	hxBasicGoodsCodeParam.setPid(0L);
        	hxBasicGoodsCodeParam.setPids("[0],");
        } else {
            Long pid = hxBasicGoodsCodeParam.getPid();
            HxBasicGoodsCode temp = hxBasicGoodsCodeService.getById(pid);
            String pids = temp.getPids();
            hxBasicGoodsCodeParam.setPid(pid);
            hxBasicGoodsCodeParam.setPids(pids + "[" + pid + "],");
        }
        this.hxBasicGoodsCodeService.add(hxBasicGoodsCodeParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
    	hxBasicGoodsCodeParam.setUpdateUser(userService.getcurrentUser().getName());

        if (ToolUtil.isEmpty(hxBasicGoodsCodeParam.getPid()) || hxBasicGoodsCodeParam.getPid().equals(0L)) {
        	hxBasicGoodsCodeParam.setPid(0L);
        	hxBasicGoodsCodeParam.setPids("[0],");
        } else {
            Long pid = hxBasicGoodsCodeParam.getPid();
            HxBasicGoodsCode temp = hxBasicGoodsCodeService.getById(pid);
            String pids = temp.getPids();
            hxBasicGoodsCodeParam.setPid(pid);
            hxBasicGoodsCodeParam.setPids(pids + "[" + pid + "],");
        }
        this.hxBasicGoodsCodeService.update(hxBasicGoodsCodeParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
    	List<HxBasicGoodsCodeResult> list = hxBasicGoodsCodeService.likePids(hxBasicGoodsCodeParam.getId());
    	for (HxBasicGoodsCodeResult r : list) {
    		HxBasicGoodsCodeParam p1 = new HxBasicGoodsCodeParam();
    		p1.setId(r.getId());
    		hxBasicGoodsCodeService.delete(p1);
		}
        this.hxBasicGoodsCodeService.delete(hxBasicGoodsCodeParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
        HxBasicGoodsCode detail = this.hxBasicGoodsCodeService.getById(hxBasicGoodsCodeParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 获取部门的tree列表，ztree格式
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping(value = "/tree")
    @ResponseBody
    public List<ZTreeNode> tree(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsCodeParam.setDeptId(user.getDeptId());
    	hxBasicGoodsCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicGoodsCodeParam.setOperateId(user.getOperateId());
        List<ZTreeNode> tree = this.hxBasicGoodsCodeService.tree(hxBasicGoodsCodeParam);
		return tree;
    }

    /**
     * 获取部门的tree列表，ztree格式
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping(value = "/treeo")
    @ResponseBody
    public List<ZTreeNode> treeo(HxBasicGoodsCodeParam hxBasicGoodsCodeParam) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsCodeParam.setDeptId(user.getDeptId());
    	hxBasicGoodsCodeParam.setDeliverId(user.getDeliverId());
    	hxBasicGoodsCodeParam.setOperateId(user.getOperateId());
        List<ZTreeNode> tree = this.hxBasicGoodsCodeService.tree(hxBasicGoodsCodeParam);
        tree.add(ZTreeNode.createParent());
		return tree;
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2024-01-10
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxBasicGoodsCodeParam hxBasicGoodsCodeParam,String condition ) {
    	User user = userService.getcurrentUser();
    	hxBasicGoodsCodeParam.setDeptId(user.getDeptId());
    	hxBasicGoodsCodeParam.setDeliverId(user.getDeliverId());
        return this.hxBasicGoodsCodeService.findPageBySpec(hxBasicGoodsCodeParam,condition,user.getOperateId());
    }

}


